import fs from 'node:fs';
import path from 'node:path';
import bpjs from 'protobufjs-cli/pbjs';
import pbts from 'protobufjs-cli/pbts';

async function main() {
  const protoPath = path.resolve('src/modules/socket/proto/main.proto');

  try {
    fs.accessSync(protoPath);

    const jsPath = await bpTojs(protoPath);
    await jsToDts(jsPath);

    console.log(`✅ ${path}`);
  }
  catch (err) {
    console.log(`🛑 ${path} ${String(err)}`);
  }
}

main();

async function bpTojs(protoPath: string) {
  const jsPath = protoPath.replace(/\.\w+$/, '.js');

  return new Promise<string>((resolve, reject) => {
    bpjs.main(
      ['-t', 'static-module', '-w', 'es6', '-o', jsPath, protoPath],
      err => err ? reject(err) : resolve(jsPath),
    );
  });
}

async function jsToDts(jsPath: string) {
  const dtsPath = jsPath.replace(/\.\w+$/, '.d.ts');

  return new Promise<string>((resolve, reject) => {
    pbts.main(
      ['-o', dtsPath, jsPath, '-m'],
      err => err ? reject(err) : resolve(dtsPath),
    );
  });
}
